using Microsoft.EntityFrameworkCore;
using StudentApi.DB;
using StudentApi.Models;

namespace StudentApi.Interfaces;

public class Repository<T> : IRepository<T> where T : EntityBase
{

    private readonly ApiDbContext _db;
    private DbSet<T> _tb;
    public Repository(ApiDbContext db)
    {
        _db = db;
        _tb = db.Set<T>();
    }

    public async Task<T> AddAsync(T entity)
    {
        await _tb.AddAsync(entity);
        await _db.SaveChangesAsync();
        return entity;
    }

    public async Task<T> DelAsync(T entity)
    {
        _tb.Remove(entity);
        await _db.SaveChangesAsync();
        return entity;
    }

    public async Task<T> EditAsync(T entity)
    {
        _tb.Update(entity);
        await _db.SaveChangesAsync();
        return entity;
    }
    public async Task<T?> GetByIdAsync(Guid id)
    {
        var obj = await _tb.FindAsync(id);
        return obj;
    }

    public async Task<List<T>> GetAllAsync()
    {
        return await _tb.ToListAsync();
    }
}